package edu.sctu.zcy.month201506.day20150619;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Created by user24 on 2015/6/19.
 */
public class HttpPost1 {

    private URL url;

    public HttpPost1(String url) {

        try {
            this.url = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    public void sendPost(HashMap<String, String> hashMap) {

        String params = getParams(hashMap);
        byte[] bytes = new byte[1024*2];

        try {
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.connect();

//            if (httpURLConnection.getResponseCode() == 200) {
//
//                System.out.println("POST请求成功");

                OutputStream outputStream = httpURLConnection.getOutputStream();
                outputStream.write(params.getBytes());
                outputStream.close();

            System.out.println(httpURLConnection.getResponseMessage());

            InputStream inputStream = httpURLConnection.getInputStream();

            int line;
            while ((line = inputStream.read(bytes)) != -1){
                System.out.println(new String(bytes,0,line));
            }

//                System.out.println(httpURLConnection.getResponseMessage());
//            } else {
//
//                System.out.println("POST请求失败");
//            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public String getParams(HashMap<String, String> hashMap) {

        StringBuffer stringBuffer = new StringBuffer();
        String s;

        Set<Map.Entry<String,String>> hashMap1 = hashMap.entrySet();

        for(Map.Entry<String,String> h : hashMap1){

           stringBuffer.append(h.getKey()+"="+h.getValue()+"&");

        }
        s = stringBuffer.toString();
      return s;

    }
}
